package com.ruoyi.spider;

import cn.hutool.core.util.ObjectUtil;
import com.ruoyi.Processor.HtmlParserService;
import com.ruoyi.common.entity.*;
import com.ruoyi.common.enums.SpiderKey;
import com.ruoyi.common.service.CategoryService;
import com.ruoyi.common.service.IProjectItemsService;
import com.ruoyi.common.service.ProjectService;
import lombok.AllArgsConstructor;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;
import us.codecraft.webmagic.ResultItems;
import us.codecraft.webmagic.Task;
import us.codecraft.webmagic.pipeline.Pipeline;

import java.time.LocalDate;
import java.time.LocalDateTime;
import java.util.*;
import java.util.stream.Collectors;

import static org.jsoup.nodes.Document.OutputSettings.Syntax.html;

/**
 * @author 0617
 */
@Slf4j
@Component
@Transactional
@AllArgsConstructor
public class ProjectPipeline implements Pipeline {
    private  ProjectService projectService;
    private  IProjectItemsService projectItemsService;
    private  CategoryService categoryService;


    @Override
    @Transactional
    public void process(ResultItems resultItems, Task task) {
        BaiduUrlResource detailResource = resultItems.get(SpiderKey.SPIDER_KEY_DEATIL.getKey());
        if (detailResource == null) {
            log.warn("⚠️ 未获取到详情资源数据");
            return;
        }

        log.info("📌 获取到的详情数据: {}", detailResource);

        // 处理分类逻辑
        String categoryName = detailResource.getCategoryName();
        Category category = categoryService.selectExist(categoryName);
        if (category == null) {
            log.info("🆕 创建新分类: {}", categoryName);
            category = new Category();
            category.setTitle(categoryName);
            category.setIcon(detailResource.getCoverImage());
            category.setSortOrder(0);
            category.setIsActive(1);
            category.setCreatedAt(LocalDateTime.now());
            category = categoryService.saveSpiderCategory(category);
        }
        HtmlParserService parserService = new HtmlParserService();
        Project project = parserService.parseHtmlToProject(detailResource.getContent());
        // 创建项目主体


        project.setTitle(detailResource.getTitle());
        project.setCreateTime(LocalDateTime.now());
        project.setTag(category.getTitle());
        project.setContentTitle(detailResource.getTitle());
        project.setResourceUrl(detailResource.getShowPanInfo());
        project.setStatus(1);
        project.setCreateBy("Spider");
        projectService.save(project);


        // 创建项目条目
        ProjectItem projectItems = new ProjectItem();
        projectItems.setTitle(detailResource.getTitle());
        projectItems.setDescription(detailResource.getDescription());
        projectItems.setIconClass(detailResource.getShowCoverImage());
        projectItems.setCreateTime(LocalDate.now());
        projectItems.setCategoryId(Long.valueOf(category.getId()));
        projectItems.setProjectId(project.getId());
        projectItems.setCreateBy("Spider");
        projectItemsService.save(projectItems);


    }



        /**
         * 使用正则表达式去除 HTML 标签
         * @param html 输入的 HTML 字符串
         * @return 纯文本
         */
        private   String removeHtmlTags(String html) {
            if (html == null || html.isEmpty()) {
                return html;
            }

            // 正则表达式匹配所有 HTML 标签：<...>
            // 同时处理标签内的换行、空白等
            return html.replaceAll("<[^>]+>", "")
                    .replaceAll("\\s+", " ")  // 将多个空白字符替换为单个空格
                    .trim();
        }

}